$(function($) {
 
	var val_add_dlg = initAddValDlg();
	var localVdlg = initCaveDlg('Vol', '本地电压曲线');
	var localPdlg = initCaveDlg('Load', '本地负荷曲线');
	//本地负荷曲线编辑
	gPageParam.localPcurveEdit=function () {
		// alert("localPcaveEdit");
		localPdlg.show();
	}

	//本地电压曲线编辑	
	gPageParam.localVcurveEdit= function () {
		// alert("localVcaveEdit");
		localVdlg.show();
	}




//窗口大小调整的时候，调整propertylayout的大小，适应屏幕的宽度
	$(window).resize(function() {
		var itemwidth = 210;

		for (var i = 6; i > 0; i--) {
			//alert($("#prpperty_layout").width());
			if ($("#property_layout").width() > itemwidth * i + 10) {

				$("#property_item_body").width(itemwidth * i + 10);
				$(".spline").width(itemwidth * i);
				break;
			}
		}

	});



	$("#comit").off().on("click", function() {
		//gPageParam.configPage.gensName

		//editGens(gPageParam.configPage.gens, {}, false, function() {
		//alert("ok");
		//alert("gen");
	});

	$("#export").off().on("click", function() {
		//alert("gen");
		var val = JSON.stringify($("#property_item_body").componentProperty('values'));
		alert(val);
		if ($('#measure_tab').data("rowData")) {
			var value = JSON.stringify($('#measure_tab').data("rowData"));
			//获取数值之后移除数据项  
			$('#measure_tab').removeData("rowData");
		}

		 
	});

	function initAddValDlg() {
		var time = $('#time').jqxDateTimeInput({
			width: '120px',
			height: '25px',
			formatString: 'HH:mm',
			showCalendarButton: false
		});
		var value_high = $('#value_high').jqxNumberInput({
			width: '120px',
			height: '25px',
			inputMode: 'simple',
			spinButtons: true,
			min: 0,
			max: 1000
		});

		var value_low = $('#value_low').jqxNumberInput({
			width: '120px',
			height: '25px',
			inputMode: 'simple',
			spinButtons: true,
			min: 0,
			max: 1000
		});
		var _call = function(dlg) {
			alert("ok1");
		};
		var val_add_dlg = $('#val_add_dlg').jqxWindow({

			title: '时间-限值添加',
			height: 200,
			width: 220,
			resizable: false,
			isModal: true,
			modalOpacity: 0.3,
			theme: theme,
			autoOpen: false,
			//okButton: $('#val_add_dlg #ok'),
			cancelButton: $('#val_add_dlg #cancel'),
			initContent: function() {

			}
		});
		$('#val_add_dlg #ok').off().on("click", function(event) {



			//校验数据是否合法，调用回调函数
			if (value_high.jqxNumberInput('val') < value_low.jqxNumberInput('val')) {
				$.config.alertDlg("上限值必须大于下限值！");
			} else {
				val_add_dlg.time = function() {
					var _tim = time.jqxDateTimeInput('val', 'date');
					//console.dir(_tim.format('yyyy-MM-dd hh:mm:ss.zzz'));
					return _tim.hour_mi_int();
					//alert(_tim);
					//return 100;
				};
				val_add_dlg.value_high = value_high.jqxNumberInput('val');
				val_add_dlg.value_low = value_low.jqxNumberInput('val');
				_call(val_add_dlg);
			}

		});
		val_add_dlg.show = function(callback) {
			$(this).jqxWindow("open");
			_call = callback;
		}

		return val_add_dlg;

	}

	$(':button').jqxButton({
		theme: theme,
		width: '65px'
	});


//本地电压曲线对话框
	function initCaveDlg(type, title) {
		var okbtn = $('#curve_dlg_' + type + ' #ok');
		var cancelbtn = $('#curve_dlg_' + type + ' #cancel');
		var addbtn = $('#curve_dlg_' + type + ' #add');
		var deletebtn = $('#curve_dlg_' + type + ' #delete');
		var submitbtn = $('#curve_dlg_' + type + ' #submit');
           //电压曲线表格
		function initGRID(type) {
			var url = "table_xml/curve/" + type + "Curve.xml";
			// prepare the data
			var source = {
				datatype: "xml",
				datafields: [{
					name: 'Desc',
					map: 'm\\:properties>d\\:Desc'
				}, {
					name: 'Field',
					map: 'm\\:properties>d\\:Field'
				}, {
					name: 'DefaultValue',
					map: 'm\\:properties>d\\:DefaultValue'
				}, {
					name: 'DataType',
					map: 'm\\:properties>d\\:DataType'
				}, {
					name: 'Enum',
					map: 'm\\:properties>d\\:EnumData' //在低版本中，xml的项必须存在，且不能为空，高版本中可以不存在，且能为空，所以在没有枚举量的xml项中补填N作为占位
				}],
				root: "content",
				// record : "content",
				id: 'm\\:properties>d\\:Field',
				url: url
			};
			var datafields = [];
			var columns = [];
			var table = $('#curve_grid_' + type);
			//==加载表格数据  initTab(eqpType);
			table.loadDATA = function(type) {

				var source = {
					datatype: "csv",
					datafields: datafields,
					url: 'defaultData/curve/' + type + 'Curve.csv'
				};

				var dataAdapter = new $.jqx.dataAdapter(source, {
					async: false,
					loadError: function(xhr, status, error) {
						alert('Error loading "' + source.url + '" : ' + error);
					}
				});
				var _this = this;
				$(this).jqxGrid({
					width: '99.5%',
					height: '99.5%',
					theme: theme,
					editable: true,
					altrows: true,
					source: dataAdapter,
					selectionmode: 'singlecell', //设置选择方式
					columns: columns,
					ready: function() {



					}
					// 单元格数据变化事件，，通过对变化的捕捉，来记录变化，提交到服务端
				}).on('cellvaluechanged', function(event) {

					var field = args.datafield;
					var rowindex = args.rowindex;
					var value = args.newvalue;
					if (!value)
						return;

					var row = table.jqxGrid('getrowdata', rowindex);
					var oldvalue = args.oldvalue;
					//设置变化值到缓存中
					if (!$(this).data("rowData"))
						$(this).data("rowData", {});
					var rowData = $(this).data("rowData");
					var item = rowData[row.DayTime];
					if (item) {
						//更新的，直接更新数据，更新对应字段的数据。
						//添加的 ，不更新操作，直接更新数据。
						//删除的，提示删除一条已经备删除的记录。
						if (item.handle == 'delete') {
							console.dir("错误，更新一条需要删除的记录");
						} else {
							item.val[field] = value;
						}
					} else {
						//没有就创建一条更新的数据
						item = {};
						item.handle = 'update';
						item.val = {};
						item.val[field] = value;
					}

					rowData[row.DayTime] = item; //更新到rowdata

					$(this).data("rowData", rowData);


					// console.dir(column + '==' + row + "===" + value + $(this).attr('id'));

				});
			}
			table.addNew = function(time, high, low) {
				//按照配置文件加载进来的顺序是 0 eqpid 1 time 2 high 3 low
				// addrow null[插入的位置，如果为null，自动在尾部添加]
				var newData = {};
				newData[datafields[1].name] = time;
				newData[datafields[2].name] = high;
				newData[datafields[3].name] = low;
				console.dir(JSON.stringify(newData));

				if (!$(this).data("rowData")) {
					$(this).data("rowData", {});
				}
				var items = $(this).data("rowData");
				var item = items[time];
				//如果之前有对改时间的删除项，则修改为更新项。
				if (item) {
					item.handle = 'update';
				} else {
					//否则，新建插入项
					item = {};
					item.handle = 'insert';

				}
				item.val = {};
				item.val[datafields[2].name] = high;
				item.val[datafields[3].name] = low;
				items[time] = item;
				$(this).data("rowData", items);
				$(this).jqxGrid('addrow', null, newData);
			}

			//加载配置文件
			var dataAdapter = new $.jqx.dataAdapter(source, {
				autoBind: true,
				loadComplete: function() {

					// get data records.
					var records = dataAdapter.records;
					var length = records.length;
					for (var i = 0; i < length; i++) {
						var record = records[i];
						var fields = {};
						fields["name"] = record.Field;
						datafields.push(fields);
						var column = {};
						column["datafield"] = record.Field;
						column["text"] = record.Desc;

						//根据 配置项的多少决定是否设置宽度
						var width = table.width();

						// if ((length * 80) > width)
						// 	column["width"] = 80;
						//隐藏设备ID列
						if (record.Field == "EqptId")
							continue;
						//设置时间列的编辑控件
						if (record.Field == "DayTime") {
							column["columntype"] = 'datetimeinput';
							column["editable"] = false;

							column["cellsrenderer"] = function(row, datafield, value, defaultHtml, columnproperties) {
								//将数字转化为时间，如果数值是空字符串，返回00：00
								var text = "00:00";
								if (value == '') {

								} else {

									text = $.config.TimeFromInt(value);
								}

								var date = new Date(value);
								var element = $(defaultHtml);
								element.html(text);
								return element[0].outerHTML;
							};
						} else {
							column["columntype"] = 'numberinput';
							column["createeditor"] = function(row, column, editor, celltext, cellwidth, cellheight) {
								// assign a new data source to the dropdownlist.

								editor.jqxNumberInput({
									width: cellwidth,
									height: cellheight,

									inputMode: 'simple',
									spinButtons: true,
									min: 0,
									max: 1000
								});


							};
							column["initeditor"] = function(row, cellvalue, editor, celltext, cellwidth, cellheight) {
								editor.jqxNumberInput({

									digits: cellvalue
								});
							}
							column["geteditorvalue"] = function(row, cellvalue, editor) {
								// return the editor's value.
								return editor.find('input').val();
							}



						}

						columns.push(column);
					}

					//数据加载完成 初始化表格
					table.loadDATA(type);
				}

			});
			return table;
		}
		var table = initGRID(type);
		//曲线设置对话框
		var add_gen_type_dlg = $('#curve_dlg_' + type).jqxWindow({
			// maxHeight: 150,
			// maxWidth: 280,
			// minHeight: 30,
			// minWidth: 250,
			title: title,
			height: 530,
			width: 370,
			resizable: false,
			isModal: true,
			modalOpacity: 0.3,
			theme: theme,
			autoOpen: false,
			okButton: okbtn,
			cancelButton: cancelbtn,
			initContent: function() {

				addbtn.on('click', function() {
					val_add_dlg.show(function(dlg) {
						//1 校验事件重复,并将时间转化为0~1440的数值。通过$(this).data("rowData").校验时间
						//读取当前已经配置的数据
						// 1 设置时间
						var rows = table.jqxGrid('getrows');
						var result = "";
						var time = dlg.time();
						for (var i = 0; i < rows.length; i++) {
							var row = rows[i];
							if (row.DayTime == time) {
								$.config.alertDlg("时间" + $.config.TimeFromInt(time) + "已经重复了！");
								return;
							}
						}
						//	console.dir(dlg.time() + '==' + dlg.value_high + '==' + dlg.value_low);
						table.addNew(time, dlg.value_high, dlg.value_low);
						//2 校验上限必须大于下限



						dlg.jqxWindow("close");
						//alert($(this).html());
						//	table.jqxGrid('addrow', null, {});
					});

				});
				deletebtn.on('click', function() {
					//设置为 'singlecell', 'multiplecells' or 'multiplecellsextended' 需要使用getselectedcell 方法
					var cell = table.jqxGrid('getselectedcell');
					var selectedrowindex = cell.rowindex;
					// var selectedrowindex = table.jqxGrid('getselectedrowindex');
					var rowscount = table.jqxGrid('getdatainformation').rowscount;
					if (selectedrowindex >= 0 && selectedrowindex < rowscount) {
						var id = table.jqxGrid('getrowid', selectedrowindex);

						var row = table.jqxGrid('getrowdata', 0);
						//alert(data.firstname + " " + data.lastname);

						if (!table.data("rowData")) {
							table.data("rowData", {});
						}
						var items = table.data("rowData");
						var item = items[row.DayTime]
						if (item) {
							//更新的，标识为删除。
							//添加的，直接删除
							if (item.handle == 'update') {
								item.handle = 'delete';
							} else {
								delete items[row.DAYTIME];

							}
						} else {
							//没有该项，添加，并标识为删除
							item = {};
							item.handle = 'delete';
							items[row.DayTime] = item;
						}
						table.data("rowData", items);

						var commit = table.jqxGrid('deleterow', id);
					}
				});
				submitbtn.on('click', function() {
					var data = table.data("rowData");
					alert(JSON.stringify(data));
					if (table.data("rowData")) {
						var data = table.removeData("rowData");

					}

				});



				okbtn.focus();
			}
		}).on("close", function(event) {
			if (event.type === 'close') {

				if (event.args.dialogResult.OK) {



				} else if (event.args.dialogResult.Cancel) {

				} else {

				}
			}
		});
		add_gen_type_dlg.show = function() {
			$(this).jqxWindow("open");
		}


		return add_gen_type_dlg;
	}

});